<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('编辑虚拟用况组')" />
    <link th:href="@{/css/common.css}" rel="stylesheet"/>
    <link th:href="@{/css/edit.css}" rel="stylesheet"/>
    <link th:href="@{/js/plugins/dragula/dragula.css}" rel="stylesheet"/>
    <script th:src="@{/js/plugins/dragula/dragula.js}"></script>
    <th:block th:include="include :: select2-css" />
    <style type="text/css">
        .red {
            color: red !important;
        }

        body .layer-ext-moon .layui-layer-btn .selfBtn {
            background: #f60 !important;
            color: #fff !important;
            border: 1px solid #f60 !important;
            border-radius: 3px !important;
            float: right;
        }
    </style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content ">
    <div class="col-md-12">
        <div class="header buff-header">
            <h4 class="fz16" th:text="${virtualUsageGroup.groupName}">创建版本</h4>
        </div>
        <div class="row">
            <div class="col-md-6 left">
                <ul class="nav nav-tabs first-navtabs" role="tablist">
                    <li class="active"><a href="#left-one" role="tab" data-toggle="tab">方法设计</a></li>
                    <li><a href="#left-two" role="tab" data-toggle="tab">编辑组</a></li>
                    <li><a href="#left-three" role="tab" data-toggle="tab" onclick="virtualUsage()">虚拟用况</a></li>
                </ul>
                <div class="tab-content">
                    <div class="content tab-pane active" role="tabpanel" id="left-one">
                        <ul class="nav nav-tabs" role="tablist">
                            <li class="active"><a href="#params-in" role="tab" data-toggle="tab" onclick="clickTab(1)">入参</a></li>
                            <li><a href="#params-out" role="tab" data-toggle="tab" onclick="clickTab(2)">出参</a></li>
                            <span class="pull-right">
                                <a class="btn btn-primary btn-rounded btn-sm addFieldBtn" style="background-color:#0088ff;line-height: 1;">添加字段</a>
                                <a class="btn btn-primary btn-rounded btn-sm addDataMapBtn" style="margin-left:10px;background-color:#0088ff;line-height: 1;">添加数据集</a>
                                <a class="btn btn-primary btn-rounded btn-sm deleteBtn" style="margin-left:10px;background-color:#0088ff;line-height: 1;">批量删除</a>
                            </span>
                        </ul>
                        <div class="tab-content paramSelect">
                            <div role="tabpanel" class="tab-pane active paramList" id="params-in">
                            </div>
                            <div role="tabpanel" class="tab-pane paramList" id="params-out">
                            </div>
                        </div>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="left-two">
                        <div class="ibox-content">
                            <form class="form-horizontal m-t" id="bffForm" th:object="${virtualUsageGroup}">
                                <input id="id" name="id" th:field="*{id}" type="hidden"/>
                                <input id="interfaceId" name="interfaceId" th:field="*{interfaceId}" type="hidden"/>
                                <div class="form-group">
                                    <div class="col-sm-12 pull-right">
                                        <input id="groupName" name="groupName" th:field="*{groupName}" type="text" class="form-control" placeholder="输入组名称">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="pull-left control-label">动词：</label>
                                    <div class="col-sm-4 pull-right">
                                        <select name="operateType" id="operateType" class="form-control m-b" th:with="type=${@dict.getType('operateType')}">
                                            <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{operateType}"></option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="pull-left control-label is-required">归属域：</label>
                                    <div class="col-sm-4 pull-right">
                                        <select name="domainId" id="domainId" class="form-control m-b" required>
                                            <option th:each="dict : ${domainInfoList}" th:text="${dict.domainName}" th:value="${dict.id}" th:field="*{domainId}"></option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="pull-left control-label is-required">归属域对象：</label>
                                    <div class="col-sm-4 pull-right">
                                        <select name="domainObjectId" id="domainObjectId" class="form-control m-b" required>
                                            <option th:each="dict : ${domainObjectList}" th:text="${dict.objectName}" th:value="${dict.id}" th:field="*{domainObjectId}"></option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-3 control-label">方法名称：</label>
                                    <div class="pull-right">
                                        <input  name="methodName" id="methodName" th:field="*{methodName}" type="text" class="form-control" placeholder="输入方法名称" required>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">入参DTO名称：</label>
                                    <div class="pull-right">
                                        <input  name="inParamDtoName" id="inParamDtoName" th:field="*{inParamDtoName}" type="text" class="form-control" placeholder="输入入参DTO名称" required>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">出参DTO名称：</label>
                                    <div class="pull-right">
                                        <input  name="outParamDtoName" id="outParamDtoName" th:field="*{outParamDtoName}" type="text" class="form-control" placeholder="输入出参DTO名称" required>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">是否是主</label>
                                    <div class="pull-right">
                                        <select name="isMaster" id="isMaster" class="form-control noselect2" th:with="type=${@dict.getType('masterOrSlave')}">
                                            <option value="0">请选择</option>
                                            <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{isMaster}"></option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-12">
                                        <textarea id="groupDescription" name="groupDescription" class="form-control" placeholder="输入描述信息" style="height: 96px;">[[*{groupDescription}]]</textarea>
                                    </div>
                                </div>
                                <div class="form-group" style="text-align: center;">
                                    <button onclick="submitHandler()" class="btn btn-primary btn-rounded btn-sm" style="height: 32px;line-height: 1;width: 132px;background: #0088FF;margin-top: 32px;" type="button">保存</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="left-three">
                    </div>
                </div>
            </div>
            <div class="col-md-6 right">
                <ul class="nav nav-tabs first-navtabs contentTab" role="tablist">
                    <li class="active"><a href="#content-preview" role="tab" data-action = "" data-toggle="tab">预览</a></li>
                </ul>
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane active mt20 " id="content-preview">
                        <div class="ibox-content content-preview">
                            <div class="panel-body">
                                <div class="panel-group" id="accordion">
                                    <div class="panel panel-default">
                                        <div class="panel-heading" data-toggle="collapse" href="#collapse0">
                                            <div class="panel-title">
                                                <div class="pull-left" style="margin-right: 20px;">
                                                    [[${virtualUsageGroup.groupName}]]
                                                </div>
                                            </div>
                                        </div>
                                        <div id="collapse0" class="panel-collapse collapse in">
                                            <dl class="dl-horizontal">
                                                <dt>方法描述</dt>
                                                <dd id="interfaceDescriptionDd">[[${virtualUsageGroup.groupDescription}]]</dd>
                                            </dl>
                                            <div class="panel-tit">参数</div>
                                        </div>
                                    </div>
                                    <div class="panel-tit" id="virtualUsage">虚拟用况</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: select2-js" />
<script th:inline="javascript">
    var domainInfoList = [[${domainInfoList}]];
    var domainObjectList = [[${domainObjectList}]];
    var processBranchId = [[${processBranchId}]];
    var prefix = ctx + "interface/interface";
    $("body").on('click', ".paramList .icon-jian", function(e) {
        //删除对应数据
        var removeNode1 = $(this).parents(".list-item").parent(".more");
        var removeNode2 = $(this).parents(".list-item");
        var parentNode = $(this).parent();
        var type = parentNode.attr('data-type');
        var id = parentNode.attr('data-id');
        var url = prefix + "/removeField/" + id;
        if (type == 2) {
            url = prefix + "/removeParamsField/" + id;
        }
        var config = {
            url: url,
            type: "get",
            dataType: "json",
            data: null,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.modal.closeLoading();
                if (result.code == web_status.SUCCESS) {
                    removeNode1.remove();
                    removeNode2.remove();
                    loadInterfaceParams();
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        };
        $.ajax(config);
    }).on('click', ".listInterface .icon-jian", function(e) {
        //删除对应数据
        var removeNode1 = $(this).parents(".list-item").parent(".more");
        var removeNode2 = $(this).parents(".list-item");
        var parentNode = $(this).parent();
        var id = parentNode.attr('virtualusagegroupdetailid');
        var url = ctx + "virtualUsageGroupDetail/virtualUsageGroupDetail/remove?ids=" + id + "&virtualUsageGroupId="+$("#id").val();
        var config = {
            url: url,
            type: "POST",
            dataType: "json",
            data: null,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.modal.closeLoading();
                if (result.code == web_status.SUCCESS) {
                    removeNode1.remove();
                    removeNode2.remove();
                    virtualUsage();
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        };
        $.ajax(config);
    }).on("click",".addVirtualUsageBtn",function(){
        var btn = ['确定', '取消','<span style = "color:#000000">已选择<span id="virtualUsageSelected">0</span>项</span>'];
        var options = {
            title: '选择虚拟用况接口',
            height: "600",
            url: ctx + "virtualUsageGroup/virtualUsageGroup/virtual_usage_choose/" + $("#id").val(),
            btn: btn,
            callBack: function (index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler(index, layero);
                virtualUsage();
                return false;
            }
        };
        $.modal.openOptions(options);
    }).on('click','.virtualUsage .panel-heading',function(){
        var idName = $(this).attr("href");
        $(idName).html().length ==0 && paramList(idName, $(this).data("id"), 3);
    }).on('change', '#domainId', function () {
        var id = $(this).val();
        var config = {
            url: ctx + "domainInfo/domainInfo/domainObjectList?id="+id,
            type: "POST",
            dataType: "json",
            data: null,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.modal.closeLoading();
                $("#domainObjectId").empty();
                domainObjectList = null;
                if (result.data && result.data.length > 0) {
                    domainObjectList = result.data;
                    for (var i=0; i<result.data.length; i++) {
                        $("#domainObjectId").append("<option value='"+result.data[i].id+"'>"+result.data[i].objectName+"</option>");
                    }
                }
                changeData()
            }
        };
        $.ajax(config);
    }).on('change', '#domainObjectId', function () {
        changeData();
    }).on('change', '#operateType', function () {
        changeData();
    });

    function changeData() {
        var domainId = $("#domainId").val();
        var domainObjectId = $("#domainObjectId").val();
        var operateType = $('#operateType').val();

        $("#methodName").val('');
        $("#inParamDtoName").val('');
        $("#outParamDtoName").val('');
        var objectEnName = null, domainEnName = null;

        if (domainId) {
            for(var i=0; i < domainInfoList.length; i++) {
                if (domainId == domainInfoList[i].id) {
                    domainEnName = domainInfoList[i].domainEnName;
                    break;
                }
            }
        } else {
            return;
        }
        if (domainObjectId) {
            for(var i=0; i < domainObjectList.length; i++) {
                if (domainObjectId == domainObjectList[i].id) {
                    objectEnName = domainObjectList[i].objectEnName;
                    break;
                }
            }
        } else {
            return;
        }
        $("#inParamDtoName").val(objectEnName + "ReqDto");
        $("#outParamDtoName").val(objectEnName + "RespDto");
        var tail;
        objectEnName = objectEnName.charAt(0).toUpperCase() + objectEnName.slice(1);
        if (operateType.indexOf('_') >= 0) {
            tail = operateType.replace("_", objectEnName);
        } else {
            tail = operateType + objectEnName
        }
        $("#methodName").val(tail);

    }
    //changeData();
    function virtualUsage() {
        var config = {
            url: ctx + "virtualUsageGroup/virtualUsageGroup/virtualUsageList?id="+$("#id").val(),
            type: "post",
            dataType: "json",
            data: null,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.modal.closeLoading();
                if (result.code == web_status.SUCCESS) {
                    var data = {};
                    data.list = result.data || [];
                    var paramsTplHtml = $("#virtualUsageTpl").html();
                    laytpl(paramsTplHtml).render(data, function (html) {
                        $("#left-three").empty();
                        $("#left-three").append(html);
                    });
                    initListInterfaceDragula();

                    paramsTplHtml = $("#virtualUsageTpl2").html();
                    laytpl(paramsTplHtml).render(data, function (html) {
                        $("#virtualUsage").nextAll().remove();
                        $("#virtualUsage").after(html);
                    });
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        };
        $.ajax(config);
    }

    function initListInterfaceDragula() {
        var containers = $('.listInterface').toArray();
        dragula(containers, {
            accepts: function(el, target, source, sibling) {
                return target == source;
            }
        }).on('drop', function(el, container) {
            //拖动结束后执行方法
            var virtualUsageIds = [];
            $(".listInterface").find('.list-item').each(function(){
                var data = {};
                if ($(this).attr('data-id') && $(this).attr('data-id') != 'undefined' && $(this).attr('data-id') != 'null') {
                    data.id = $(this).attr('data-id');
                }
                virtualUsageIds.push(data.id);
            });
            var virtualUsageGroupDetail = {
                groupId:$("#id").val(),
                interfaceId:$("#interfaceId").val(),
                virtualUsageIds:virtualUsageIds
            }
            var config = {
                url: ctx + "virtualUsageGroupDetail/virtualUsageGroupDetail/updateInterfaceSort",
                type: "post",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                data: JSON.stringify(virtualUsageGroupDetail),
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function(result) {
                    $.modal.closeLoading();
                    if (result.code == web_status.SUCCESS) {
                        virtualUsage();
                        //loadInterfaceParams();
                    } else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg)
                    } else {
                        $.modal.alertError(result.msg);
                    }
                }
            };
            $.ajax(config);
        })
    }

    function submitHandler() {
        var config = {
            url: ctx + "virtualUsageGroup/virtualUsageGroup/edit",
            type: "post",
            // contentType: "application/json;charset=utf-8",
            dataType: "json",
            data: $('#bffForm').serialize(),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.modal.closeLoading();
                if (result.code == web_status.SUCCESS) {
                    $.modal.msgSuccess("保存成功");
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        };
        $.ajax(config);
    }

    var paramType = 1;
    function clickTab(type) {
        paramType = type;
    }

    $(".addFieldBtn").click(function() {
        var paramName = "入参";
        if (paramType == 2) {
            paramName="出参";
        }
        var btn = ['确定', '取消','<span style = "color:#000000">已选择<span id="fieldSelected">0</span>项</span>'];
        var options = {
            title: '选择'+paramName+'字段',
            height: "600",
            url: ctx + "virtualUsageGroup/virtualUsageGroup/field_choose/" + $("#id").val() +"/" + paramType,
            btn: btn,
            callBack: function (index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler(index, layero);
                loadInterfaceParams();
                return false;
            }
        };
        $.modal.openOptions(options);
    });

    $(".addDataMapBtn").click(function() {
        let btn = ['确定', '取消','<img th:src="@{/img/Icon-add.png}" class="icon" style="padding-right: 4px;" />新增结果集',];
        var paramName = "入参";
        var domainObjectId = $("#domainObjectId").val() || 0;
        if (paramType == 2) {
            paramName="出参";
        }
        let options = {
            title: '选择'+paramName+'数据集',
            height: "600",
            url: prefix + "/data_map_choose/" + paramType + "/" + $("#id").val() + "/5",
            btn: btn,
            callBack: function (index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler(index, layero);
                loadInterfaceParams();
                return false;
            },
            btn3: function(index2, layero2) {
                layer.close(index2);
                createParams(domainObjectId);
                return false;
            }

        };
        $.modal.openOptions(options);
    });


    function createParams(domainObjectId) {
        let btn = ['保存', '取消'];
        let options = {
            title: '创建数据集',
            width: "700",
            height: "400",
            url: prefix + "/data_map_create/" + paramType + "/"+domainObjectId + "/" + $("#id").val() + "/5",
            btn: btn,
            callBack: function (index, layero) {
                var iframeWin = layero.find('iframe')[0];
                var flag = iframeWin.contentWindow.submitHandler(index, layero);
                if (flag) {
                    layer.close(index);
                    loadInterfaceParams();
                } else {
                    return flag;
                }
            }
        };
        $.modal.openOptions(options);
    }

    /**
     * 添加数据集字段
     * @param id
     */
    function addParamsField(id) {
        var btn = ['确定', '取消','<span style = "color:#000000">已选择<span id="fieldSelected">0</span>项</span>'];
        var options = {
            title: '选择数据集字段',
            height: "600",
            url: ctx + "virtualUsageGroup/virtualUsageGroup/params_field_choose/" + $("#id").val() +"/" + paramType + "/" + id,
            btn: btn,
            callBack: function (index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler(index, layero);
                loadInterfaceParams();
                return false;
            }
        };
        $.modal.openOptions(options);
    }

    $(".deleteBtn").click(function () {
        var fieldDiv = $("#params-in");
        if (paramType == 2) {
            fieldDiv = $("#params-out");
        }
        fieldDiv.find(".icon-jian").each(function () {
            //删除对应数据
            var removeNode1 = $(this).parents(".list-item").parent(".more");
            var removeNode2 = $(this).parents(".list-item");
            var parentNode = $(this).parent();
            var type = parentNode.attr('data-type');
            var id = parentNode.attr('data-id');
            var url = prefix + "/removeField/" + id;
            if (type == 2) {
                url = prefix + "/removeParamsField/" + id;
            }
            var config = {
                url: url,
                type: "get",
                dataType: "json",
                async: false,
                data: null,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function(result) {
                    $.modal.closeLoading();
                    if (result.code == web_status.SUCCESS) {
                        removeNode1.remove();
                        removeNode2.remove();
                    } else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg)
                    } else {
                        $.modal.alertError(result.msg);
                    }
                }
            };
            $.ajax(config);
        });
        loadInterfaceParams();
    })
    $(function() {
        loadInterfaceParams();

        /**标签切换事件*/
        $(".contentTab a").click(function (e) {
            var action = $(this).data("action");
            if(action) {
                window[action]();
            }
        });
    })

    /**
     * 加载 接口参数
     */
    function loadInterfaceParams() {
        var id = $("#id").val();
        var data = "interfaceType=5&interfaceId="+id;
        if (processBranchId) {
            data = data + "&processBranchId=" + processBranchId;
        }
        var config = {
            url: prefix + "/paramList",
            type: "post",
            dataType: "json",
            data: data,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.modal.closeLoading();
                $("#params-in").empty();
                $("#params-out").empty();
                if (result.code == web_status.SUCCESS) {
                    var resultJson = result.data;
                    if(!resultJson) {
                        return false;
                    }
                    initParam(resultJson.requestList, "#params-in");
                    initParam(resultJson.responseList, "#params-out");
                    doPreview(resultJson);
                    initDragula();
                    //initSelectChange();
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        };
        $.ajax(config);
    }

    function initParam(params, id) {
        var data = {};
        data.list = params;
        if ("#params-out" == id) {
            data.isInParam=0;
        } else {
            data.isInParam=1;
        }
        data.processBranchId=processBranchId;

        var paramsTplHtml = $("#paramsTpl").html();
        laytpl(paramsTplHtml).render(data, function (html) {
            $(id).append(html);
        });
    }

    function initDragula() {
        var containers = $('.list').toArray();
        containers = containers.concat($('.sec-list').toArray());
        dragula(containers, {
            accepts: function(el, target, source, sibling) {
                return target == source;
            }
        }).on('drop', function(el, container) {
            var data = {
                'id' : $("#id").val(),
                'fbType':'5'
            };
            var interfaceParamReqList = [];
            interfaceParamReqList = getParams("#params-in", "1", interfaceParamReqList);
            interfaceParamReqList = getParams("#params-out", "2", interfaceParamReqList);
            data.interfaceParamReqList = interfaceParamReqList;
            var config = {
                url: prefix + "/updateSort",
                type: "post",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                data: JSON.stringify(data),
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function(result) {
                    $.modal.closeLoading();
                    if (result.code == web_status.SUCCESS) {
                        loadInterfaceParams();
                    } else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg)
                    } else {
                        $.modal.alertError(result.msg);
                    }
                }
            };
            $.ajax(config);
        })
    }

    function getParams(id,isInParam, interfaceParamReqList) {
        var sortNum = 1;
        $(id).find('.no-top').each(function(){
            var data = {};
            if ($(this).attr('data-id') && $(this).attr('data-id') != 'undefined' && $(this).attr('data-id') != 'null') {
                data.id = $(this).attr('data-id');
            }
            data.objectType = $(this).attr('data-object-type');
            data.objectId = $(this).attr('data-field-id');
            data.isInParam = isInParam;
            data.sortNum = sortNum;
            sortNum ++;
            if ($(this).hasClass('more')) {
                var paramsFieldReqList = getChildParam($(this));
                if (paramsFieldReqList && paramsFieldReqList.length > 0) {
                    data.paramsFieldReqList = paramsFieldReqList;
                }
            }
            interfaceParamReqList.push(data);
        });
        return interfaceParamReqList;
    }

    function getChildParam(e) {
        var paramsFieldReqList = [];
        var sortNum = 1;
        $(e).find('.sec-list .list-item').each(function(){
            var child = {};
            if ($(this).attr('data-id') && $(this).attr('data-id') != 'undefined' && $(this).attr('data-id') != 'null') {
                child.id = $(this).attr('data-id');
            }
            child.fieldId = $(this).attr('data-field-id');
            child.sortNum = sortNum;
            sortNum ++;
            paramsFieldReqList.push(child);
        });
        return paramsFieldReqList;
    }

    /**
     * 预览
     */
    function doPreview(data) {
        var interfaceType = 5;
        data.interfaceType= interfaceType;
        var contentPreviewTplHtml = $("#contentPreviewTpl").html();

        convertResponse(data);

        laytpl(contentPreviewTplHtml).render(data, function (html) {
            $("#collapse0 .panel-body").remove();
            $("#collapse0").append(html);
        });

        $("#nonFunctionalRequirementsDd").text($("#nonFunctionalRequirements").val())
        $("#interfaceDescriptionDd").text($("#interfaceDescription").val())

        // 加载虚拟用况数据
        var virtualUsageListConfig = {
            url: ctx + "virtualUsageGroup/virtualUsageGroup/virtualUsageList?id="+$("#id").val(),
            type: "post",
            dataType: "json",
            data: null,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.modal.closeLoading();
                if (result.code == web_status.SUCCESS) {
                    var data = {};
                    data.list = result.data || [];
                    var paramsTplHtml = $("#virtualUsageTpl2").html();
                    laytpl(paramsTplHtml).render(data, function (html) {
                        $("#virtualUsage").nextAll().remove();
                        $("#virtualUsage").after(html);
                    });
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        };
        $.ajax(virtualUsageListConfig);
    }

    function paramList(idName,interfaceId,interfaceType) {
        idName = idName;
        var params = {};
        params.interfaceId = interfaceId;
        params.interfaceType = interfaceType;
        var resultJson;
        var config = {
            url: prefix + "/paramList",
            type: "POST",
            dataType: "json",
            data: params,
            success: function (result) {
                if (result && result.code == 0) {
                    var data = result.data;
                    var contentPreviewTplHtml = $("#contentPreviewTpl").html();
                    convertResponse(data);
                    data.virtualUsage=true;
                    laytpl(contentPreviewTplHtml).render(data, function (html) {
                        $(idName).empty();
                        $(idName).append(html);
                    });
                }
            }
        };
        $.ajax(config);
    }

    /**
     * 虚拟用况页面
     * @param id
     */
    function virtualUsageDetail(id) {
        $.modal.openTab("虚拟用况接口编辑", ctx + "virtualUsageGroup/virtualUsageGroup/bff_usage_params?id=" + id+"&virtualUsageGroupId="+$("#id").val());
    }

    function fieldDesign(id, type) {
        var url = prefix + "/fieldDesign?id="+id + "&type="+type;
        var width = $(window).width() - 50, height = $(window).height() - 50;
        layer.open({
            type: 2,
            area: [width + 'px', height + 'px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: "字段详细设计",
            content: url,
            btn: ['确定', '重置', '关闭'],
            // 弹层外区域关闭
            shadeClose: true,
            yes: function(index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler(index, layero);
                loadInterfaceParams();
                layer.close(index);
                return true;
            },
            btn2: function(index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.resetHandler(index, layero);
                loadInterfaceParams();
                layer.close(index);
                return true;
            },
            btn4: function(index, layero) {
                return true;
            },
            cancel: function(index) {
                return true;
            }
        });
    }

    function virtualUsageModelSelect(id) {
        var url = ctx + "interfaceinfo/virtualUsage/virtualUsageModelSelect?id="+id;
        var width = $(window).width() - 50, height = $(window).height() - 50;
        layer.open({
            type: 2,
            area: [width + 'px', height + 'px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: "虚拟用况模式选择",
            content: url,
            btn: ['确定', '重置', '关闭'],
            // 弹层外区域关闭
            shadeClose: true,
            yes: function(index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler(index, layero);
                virtualUsage();
                layer.close(index);
                return true;
            },
            btn2: function(index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.resetHandler(index, layero);
                virtualUsage();
                layer.close(index);
                return true;
            },
            btn4: function(index, layero) {
                return true;
            },
            cancel: function(index) {
                return true;
            }
        });
    }

    var interfaceInfo = [[${interfaceInfo}]];
    // 参数字段来源选择
    function inParamFieldSourceChoose(id, type) {
        var interfaceId = interfaceInfo.id;
        var fbType = interfaceInfo.fbType;
        if (fbType == '3') {
            fbType = '4';
        }
        var virtualUsageName = $("#groupName").val();
        var url = ctx + "processBranch/processBranch/fieldSourceAllSelect?interfaceId="+interfaceId+"&fbType="+fbType+"&interfaceFieldId="+id+"&interfaceFieldType="+type+"&virtualUsageId="+$("#id").val() + "&processBranchId="+processBranchId+"&virtualUsageName="+virtualUsageName+"&virtualUsageType=2";
        layer.open({
            type: 2,
            area: [800 + 'px', 600 + 'px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: "字段来源选择",
            content: url,
            btn: ['确定', '重置', '关闭'],
            // 弹层外区域关闭
            shadeClose: true,
            yes: function(index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.submitHandler(index, layero);
                loadInterfaceParams();
                return false;
            },
            btn2: function(index, layero) {
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.resetHandler(index, layero);
                loadInterfaceParams();
                return false;
            },
            btn4: function(index, layero) {
                return true;
            },
            cancel: function(index) {
                return true;
            }
        });
    }
</script>

<script id="paramsTpl" type="text/template">
    <div id="list" class="list">
        {{# layui.each(d.list, function(index, a){ }}
        {{# if(a.objectType == '2'){ }}
        <div class="more mb-12 no-top" data-id="{{a.id}}" data-field-id="{{a.fieldId}}" data-object-type="2">
            <div class="list-item">
                <span class="col-md-4"><img th:src="@{/img/Icon-yidongshu.png}" class="icon"/>{{a.fieldName}}</span>
                <span class="col-md-3">{{a.fieldEnName}}</span>
                {{# if(d.isTree){ }}
                <select class="form-control state-select nodeType">
                    <option value="">请选择</option>
                    {{# if(a.nodeType == 'F'){ }}
                    <option data="{{a.id}}" value="F" selected="selected">父</option>
                    <option data="{{a.id}}" value="Z">子</option>
                    {{# } else if(a.nodeType == 'Z'){ }}
                    <option data="{{a.id}}" value="F">父</option>
                    <option data="{{a.id}}" value="Z" selected="selected">子</option>
                    {{# } else { }}
                    <option data="{{a.id}}" value="F">父</option>
                    <option data="{{a.id}}" value="Z">子</option>
                    {{# } }}
                </select>
                {{# } }}

                <span class="pull-right" data-id="{{a.id}}" data-type="1"><img th:src="@{/img/Icon-jianshao.png}" class="icon-jian" /></span>
            </div>
            <div class="sec-list">
                {{# if(a.children){ }}
                {{# layui.each(a.children, function(index, b){ }}
                <div class="list-item" data-id="{{b.id}}" data-field-id="{{a.fieldId}}">
                    {{# if(d.isInParam == 1){ }}
                    <span class="col-md-4"><img th:src="@{/img/Icon-yidongheng.png}" class="icon" /><a class="{{# if(b.designContent  || b.fieldDescription) { }} red {{# } }}" onclick="fieldDesign({{b.id}}, 2)">{{b.fieldName}}</a></span>
                    <span class="col-md-3">{{b.fieldEnName}}</span>
                    <span class="col-md-2">{{b.fieldDataType}}</span>
                    {{# if(d.processBranchId){ }}
                    <span class="col-md-1"><a class="{{# if(b.sourceFlag) { }} red {{# } }}" onclick="inParamFieldSourceChoose({{b.id}}, 3)">来源</a></span>
                    {{# } }}
                        {{# } else { }}
                        <span class="col-md-4"><img th:src="@{/img/Icon-yidongheng.png}" class="icon" /><a onclick="setAliasName({{b.id}}, 2)">{{b.fieldName}}</a></span>
                        <span class="col-md-3">{{b.fieldEnName}}</span>
                        <span class="col-md-2">{{b.fieldDataType}}</span>

                        {{# } }}

                        <span class="pull-right" data-id="{{b.id}}" data-type="2"><img th:src="@{/img/Icon-jianshao.png}" class="icon-jian" /></span>
                </div>
                {{# }); }}
                {{# } }}
            </div>
            <div class="blue btn-add addFieldBtn" onclick="addParamsField({{a.id}})"><img th:src="@{/img/Icon-add.png}" class="icon" style="padding-right: 4px;" />选择字段</div>
        </div>
        {{# } else {}}
        {{# if(a.id){ }}
        <div class="list-item mb-12 no-top" data-id="{{a.id}}" data-field-id="{{a.fieldId}}" data-object-type="1">
            {{# if(d.isInParam == 1){ }}
            <span class="col-md-4" title="{{a.fieldName}}"><img th:src="@{/img/Icon-yidongshu.png}" class="icon"/><a class="{{# if(a.designContent || a.fieldDescription) { }} red {{# } }}" onclick="fieldDesign({{a.id}}, 1)">{{a.fieldName}}</a></span>
            <span class="col-md-3" title="{{a.fieldEnName}}">{{a.fieldEnName}}</span>
            <span class="col-md-2">{{a.fieldDataType}}</span>
            {{# if(d.processBranchId){ }}
            <span class="col-md-1"><a class="{{# if(a.sourceFlag) { }} red {{# } }}" onclick="inParamFieldSourceChoose({{a.id}}, 1)">来源</a></span>
            {{# } }}
                {{# } else { }}
                <span class="col-md-4" title="{{a.fieldName}}"><img th:src="@{/img/Icon-yidongshu.png}" class="icon"/>{{a.fieldName}}</span>
                <span class="col-md-3" title="{{a.fieldEnName}}">{{a.fieldEnName}}</span>
                <span class="col-md-2">{{a.fieldDataType}}</span>

                {{# } }}
                <span class="pull-right" data-id="{{a.id}}" data-type="1"><img th:src="@{/img/Icon-jianshao.png}" class="icon-jian"/></span>
        </div>
        {{# } }}
        {{# } }}
        {{# }); }}
    </div>
</script>

<!--关联字段模板-->
<script id="contentPreviewTpl" type="text/template">
    {{# if(d.virtualUsage){ }}
    <dl class="dl-horizontal">
        <dt>接口描述</dt>
        <dd>{{d.interfaceInfo.interfaceDescription}}</dd>
    </dl>
    <div class="panel-tit">参数</div>
    {{# } }}
    <div class="panel-body" style = "border:0px;">
        <ul class="list-group">
            <li class="list-group-item" style="height: auto; padding-top:0px;">
                <div class="re-body">
                    <p>requestBody：//输入参数</p>
                    <p>{</p>
                    <ul class="list-group field">
                        {{# layui.each(d.requestList, function(index, a){ }}
                        {{# if(a.children == null || a.children.length == 0){ }}
                        <li class="list-group-item">
                            {{# if(a.objectType=='2'){ }}
                            <p>"{{a.fieldEnName}}" : [{ // {{a.fieldName || '-'}}</p>
                            <br>
                            <p>}],</p>
                            {{# } else { }}
                            <p>"{{a.fieldEnName}}" : "{{a.mockData || '一'}}", // <span style="color: #FFA500; display: inline !important;">{{a.fieldName || '-'}}{{a.fieldEnumListName || ''}}</span></p>
                            {{# } }}
                        </li>
                        {{# } else { }}
                        <li class="list-group-item">
                            {{# if(a.children.length > 1){ }}
                            <p>"{{a.fieldEnName}}" : [{ // {{a.fieldName || '一'}}</p>
                            <ul class="list-group field">
                                {{# layui.each(a.children, function(index, b){ }}
                                <li class="list-group-item" style = "margin-left:10px;">
                                    <p>"{{b.fieldEnName}}" : "{{b.mockData || '一'}}", // <span style="color: #FFA500; display: inline !important;">{{b.fieldName || '一'}}{{b.fieldEnumListName || ''}}</span></p>
                                </li>
                                {{# }); }}
                            </ul>
                            <p>}],</p>
                            {{# } else { }}
                            <p>"{{a.fieldEnName}}" : ["{{a.children[0].mockData || '一'}}"] // {{a.fieldName || '一'}}</p>
                            {{# } }}
                        </li>
                        {{# }}}
                        {{# }); }}
                    </ul>
                    <p>}</p>
                </div>
            </li>
            <li class="list-group-item space"></li>
            <li class="list-group-item" style="height: auto;padding-top:0px;">
                <div class="re-body">
                    <p>response：//返回参数</p>
                    <p>{</p>
                    <ul class="list-group field">
                        <li class="list-group-item">
                            <p>"errCode" : "1",<span style="color: red; display: inline !important;"> //返回状态（true/false）</span></p>
                            <p>"message" : "获取成功",<span style="color: red; display: inline !important;"> //获取成功/获取失败</span></p>
                            <p>"data" : { <span style="color: red; display: inline !important;"> //返回数据</span></p>
                            <ul class="list-group field">
                                {{# layui.each(d.responseList, function(index, a){ }}
                                {{# if(a.children == null || a.children.length == 0){ }}
                                <li class="list-group-item">
                                    {{# if(a.objectType=='2'){ }}
                                    <p>"{{a.fieldEnName}}" : [{ // {{a.fieldName || '一'}}</p>
                                    <p>}],</p>
                                    {{# } else { }}
                                    {{# if(a.fieldEnName == 'total' || a.fieldEnName == 'isLastPage' || a.fieldEnName == 'pages'){ }}
                                    <p>"{{a.fieldEnName}}" : {{a.mockData}}, // <span style="color: #FFA500; display: inline !important;">{{a.fieldName || '一'}}{{a.fieldEnumListName || ''}}</span></p>
                                    {{# } else { }}
                                    <p>"{{a.fieldEnName}}" : "{{a.mockData || '一'}}", // <span style="color: #FFA500; display: inline !important;">{{a.fieldName || '一'}}{{a.fieldEnumListName || ''}}</span></p>
                                    {{# } }}
                                    {{# } }}
                                </li>
                                {{# } else { }}
                                <li class="list-group-item">
                                    <p>"{{a.fieldEnName}}" : [{ // {{a.fieldName || '一'}}</p>
                                    <ul class="list-group field">
                                        {{# layui.each(a.children, function(index, b){ }}
                                        {{# if(b.children == null || b.children.length == 0){ }}
                                        <li class="list-group-item">
                                            {{# if(b.objectType=='2'){ }}
                                            <p>"{{b.fieldEnName}}" : [{ // {{b.fieldName || '一'}}</p>
                                            <p>}],</p>
                                            {{# } else { }}
                                            <p>"{{b.fieldEnName}}" : "{{b.mockData || '一'}}", // <span style="color: #FFA500; display: inline !important;">{{b.fieldName || '一'}}{{b.fieldEnumListName || ''}}</span></p>
                                            {{# } }}
                                        </li>
                                        {{# } else { }}
                                        <li class="list-group-item">
                                            <p>"{{b.fieldEnName}}" : [{ // {{b.fieldName || '一'}}</p>
                                            <ul class="list-group field">
                                                {{# layui.each(b.children, function(index, c){ }}
                                                {{# if(c.children == null || c.children.length == 0){ }}
                                                <li class="list-group-item">
                                                    {{# if(c.objectType=='2'){ }}
                                                    <p>"{{c.fieldEnName}}" : [{ // {{c.fieldName || '一'}}</p>
                                                    <p>}],</p>
                                                    {{# } else { }}
                                                    <p>"{{c.fieldEnName}}" : "{{c.mockData || '一'}}", // <span style="color: #FFA500; display: inline !important;">{{c.fieldName || '一'}}{{c.fieldEnumListName || ''}}</span></p>
                                                    {{# } }}
                                                </li>
                                                {{# } else { }}
                                                <li class="list-group-item">
                                                    <p>"{{c.fieldEnName}}" : [{ // {{c.fieldName || '一'}}</p>
                                                    <ul class="list-group field">
                                                        {{# layui.each(c.children, function(index, d){ }}
                                                        {{# if(d.children == null || d.children.length == 0){ }}
                                                        <li class="list-group-item">
                                                            {{# if(d.objectType=='2'){ }}
                                                            <p>"{{d.fieldEnName}}" : [{ // {{d.fieldName || '一'}}</p>
                                                            <p>}],</p>
                                                            {{# } else { }}
                                                            <p>"{{d.fieldEnName}}" : "{{d.mockData || '一'}}", // <span style="color: #FFA500; display: inline !important;">{{d.fieldName || '一'}}{{d.fieldEnumListName || ''}}</span></p>
                                                            {{# } }}
                                                        </li>
                                                        {{# } else { }}
                                                        <li class="list-group-item">
                                                            <p>"{{d.fieldEnName}}" : [{ // {{d.fieldName || '一'}}</p>
                                                            <ul class="list-group field">
                                                                {{# layui.each(d.children, function(index, e){ }}
                                                                <li class="list-group-item">
                                                                    <p>"{{e.fieldEnName}}" : "{{e.mockData || '一'}}", // <span style="color: #FFA500; display: inline !important;">{{e.fieldName || '一'}}{{e.fieldEnumListName || ''}}</span></p>
                                                                </li>
                                                                {{# }); }}
                                                            </ul>
                                                            <p>}],</p>
                                                        </li>
                                                        {{# } }}
                                                        {{# }); }}
                                                    </ul>
                                                </li>
                                                {{# } }}
                                                {{# }); }}
                                            </ul>
                                            <p>}],</p>
                                        </li>
                                        {{# } }}
                                        {{# }); }}
                                    </ul>
                                    <p>}],</p>
                                </li>
                                {{# }}}
                                {{# }); }}
                            </ul>
                            <p>}</p>
                        </li>
                    </ul>
                    <p>}</p>
                </div>
            </li>
        </ul>
    </div>
</script>

<script id="virtualUsageTpl2" type="text/template">
    {{# layui.each(d.list, function(index, a){ }}
    <div class="panel panel-default virtualUsage" title="{{a.description}}">
        <div class="panel-heading" data-toggle="collapse"  href="#collapse{{a.sortNum}}" data-id="{{a.id}}">
            <h1 class="panel-title">
                <span class="badge badge-primary">{{index + 1}}</span>
                <span>{{a.slaveInterfaceName}}&nbsp;&nbsp;{{a.dubboUrl}}</span>
            </h1>
        </div>
        <div id="collapse{{a.sortNum}}" class="panel-collapse collapse"></div>
    </div>
    {{# }); }}
</script>

<script id="virtualUsageTpl" type="text/template">
    <div id="listInterface" class="listInterface">
        {{# layui.each(d.list, function(index, a){ }}
        <div class="list-item mb-12" data-id="{{a.id}}" virtualUsageGroupDetailId="{{a.virtualUsageGroupDetailId}}" title="{{a.description}}">
            <span class="col-md-4" title="{{a.slaveInterfaceName}}" onclick="virtualUsageDetail({{a.id}})"><img th:src="@{/img/Icon-yidongshu.png}" class="icon" />{{index + 1}}.{{a.slaveInterfaceName}}</span>
            <span class="col-md-3">{{a.dubboUrl}}</span>
            <span class="col-md-1">
						{{# if(a.isMaster=='Y') { }}
						主
						{{# } else if(a.isMaster=='N') { }}
						从
						{{# } }}
					</span>
            <span class="col-md-2">
						<a class="{{# if(a.model || a.selfModel) { }} red {{# } }}" onclick="virtualUsageModelSelect({{a.id}})">模式选择</a>
					</span>
            <span class="pull-right" data-id="{{a.id}}" virtualUsageGroupDetailId="{{a.virtualUsageGroupDetailId}}"><img th:src="@{/img/Icon-jianshao.png}" class="icon-jian" /></span>
        </div>
        {{# }); }}
    </div>
    <div class="color-blue btn-add">
        <span class="addVirtualUsageBtn"><img th:src="@{/img/Icon-add.png}" class="icon" style="padding-right: 4px;" />选择虚拟用况接口</span>
    </div>
</script>

</body>
</html>
